import threading
import queue
import time
from socket import *

SERVER_IP = '127.0.0.1'
LOCATION_PORT = 41234


data_file = open("./log/recv-1.txt","r",newline='')
data = data_file.read().splitlines()
line_num = 0

class FakeSenderClient:
    def __init__(self):
        print("__init__ FakeSender start")
        self.name = ''
        self._code_mode = "utf-8"
        self._reply_addr = (SERVER_IP,LOCATION_PORT)

        self._send_msg_queue = queue.Queue(64)

        self._shutdown = False

        self._term_id=0
        self.id_lock = threading.Lock()

        # start server module
        # recv msg is main threading
        # send msg is an daemon threading 
        # self.start_udp()
        
        print("__init__ FakeSender end")

    def start_udp(self):
        self.server_socket = socket(AF_INET, SOCK_DGRAM) 
        self.server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, True)
        # self.server_socket.bind((SERVER_IP, LOCATION_PORT))

        # start send msg threading
        t=threading.Thread(target=self.recv_msg,args=())
        t.daemon = True 
        t.start()   

        self.send_msg()


    def recv_msg(self):
        # while true - recv message, main threading
        while True:
            if (self._shutdown): break
            try:
                recv_msg = self.server_socket.recvfrom(1024)
            except:
                continue

            recv_msg = recv_msg[0].decode(self._code_mode) 
            print("recv msg =",recv_msg)

    def send_msg(self):
        # while true - send message
        global line_num,data
        group = 5
        count = group
        skip = True
        while True:
            try:
                line = data[line_num]
            except:
                # self.send_with_pid("0 EOF")
                while True:
                    pass
                break
            line_num+=1
            while(line==""):
                line = data[line_num]
                line_num+=1
            print("line =",line)
            # msg = input("> ")
            # if (msg=='Q' or msg=='q'):
            #     self.send_with_pid("EOF")
            #     self._shutdown = True
            #     break
            # if (msg=='reset'):
            #     self.send_with_pid("0 SYSTEM_TYPE,RESET")
            #     self.send_with_pid(line)
            # elif msg=='append':
            #     if (line.startswith('SENSOR_TYPE')):
            #         line+=',STOP_TAG'
            #     self.send_with_pid(line)
            # elif msg=='query':
            #     self.send_with_pid(line)
            #     self.send_with_pid("0 QUERY,position")
            # else:
            #     self.send_with_pid(line)
            self.send_with_pid(line)
            count-=1
            if (not skip): 
                if (count<0):
                    action = input("pause")
                    if (action=='skip'):
                        skip=True
                    count=group

            if (line.find("STOP_TAG")!=-1):
                skip = False
                count = group

            if (False
            # or line.find("SYSTEM")!=-1 
            # or line.find("ACTION_TYPE,move,0.000,0.000,-90.000") 
            # or line.find("ACTION_TYPE,move,0.000,0.000,90.000")
            # or line.find("SENSOR_TYPE,583,1748,1490,864")
            or line.find("SENSOR_TYPE,1871,512,700,1596")
            )!=-1:
                action = input("pause")
                if (action=='skip'):
                    pass
                else:
                    skip = False
                    count = group
            time.sleep(0.01)

    def get_next_tid(self):
        tid=-1
        self.id_lock.acquire()
        tid = self._term_id
        self._term_id = (tid+1)%1000
        self.id_lock.release()
        return tid

    def send_with_pid(self,to_send):
        if (to_send.startswith("#")):return
        if (to_send.find("ACTION_TYPE")!=-1):
            print("\n"*10)
        if (to_send.find("SENSOR_TYPE")!=-1):
            suffix = ""
            if (to_send.find("STOP_TAG")!=-1):
                to_send = to_send[:to_send.find("STOP_TAG")-1]
                suffix = ",STOP_TAG"
            to_send= to_send + ",{}".format(time.time()) + suffix
        # tid = self.get_next_tid()
        # msg = "{} {}".format(tid,to_send)
        msg = to_send
        print("to_send",msg)
        self.server_socket.sendto(msg.encode(self._code_mode), self._reply_addr) 

fake = FakeSenderClient()
fake.start_udp()